<?php
namespace app\admin\service;

use app\common\model\AdminModel;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\facade\Cache;
use think\Session;

class AdminService
{
    protected static $adminModel;

    /**
     * 依赖注入 AdminModel 数据库操作
     *
     * @param AdminModel $adminModel
     * @author zhouyao <994914376@qq.com>
     */
    public function __construct(AdminModel $adminModel)
    {
        self::$adminModel = $adminModel;
    }

    /**
     * 显示管理员列表
     * User: zhouyao
     * Date: 2018/9/8
     * Time: 下午1:19
     * @param $param
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws \app\common\exception\AppException
     */
    public function index($param)
    {
        if (empty($param) || !isset($param['page']) || !isset($param['limit'])) {
            app_fail(9997); // 参数异常
        }

        $where = ['is_del' => 1];
        // 获取总数
        $count = self::$adminModel->where($where)->count();
        if ($count < 1) {
            return ['data' => [], 'count' => $count];
        }
        // 查询管理员列表
        $result = self::$adminModel->where($where)
            ->page($param['page'])
            ->limit($param['limit'])
            ->order('status', 'asc')
            ->order('create_time', 'desc')
            ->select();

        $result->each(function (&$item) {
            $item->role_name = $item->role == 1 ? '超级管理员' : '普通管理员';
            $item->username = $item->user_name;
            return $item;
        });

        return ['data' => $result, 'count' => $count];
    }

    /**
     *
     * User: zhouyao
     * Date: 2018/9/8
     * Time: 上午9:52
     * @param $param
     * @return array $data
     * @throws \app\common\exception\AppException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function login($param)
    {

        if (empty($param) || !isset($param['username']) || !isset($param['password'])) {
            app_fail(9997); // 参数异常
        }

        // 查询数据库记录是否存在
        $row = self::$adminModel->where('user_name', '=', $param['username'])
            ->where('is_del', '=', 1)
            ->find();
        
        if (empty($row)) {
            app_fail(7998); //用户不存在
        }
        // 用户被禁用
        if ($row->status == 2) {
            app_fail(7999);
        }
        //检测密码是否正确
        if ($row->password !== md5($param['password'])) {
            app_fail(7997);
        }
        
        // 信息都正确 把用户信息存入 redis
        (new Session())->set('adminUser', $row);

        $data = [
            'token' => md5(time()),            //token
            'guid' => $row->id,               // 员工guid，或者渠道guid
            'token_time' => time() + 2592000, // token过期时间
            'code' => 001
        ];

        $row->save(['update_time' => date('Y-m-d H:i:s')]);

        return $data;
    }

    /**
     * 处理添加后台管理员
     * User: zhouyao
     * Date: 2018/9/8
     * Time: 下午12:42
     * @param $param
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws \app\common\exception\AppException
     */
    public function store($param)
    {
        if (empty($param) || !isset($param['name']) || !isset($param['username'])) {
            app_fail(9997);
        }

        // 检测用户名是否存在
        $admin = self::$adminModel->scope('isdel')
            ->where('user_name', '=', $param['username'])
            ->find();
        if (!empty($admin)) {
            app_fail(9995); //用户已经存在
        }

        // 执行添加操作
        try {
            self::$adminModel->create([
                'name' => $param['name'],
                'user_name' => $param['username'],
                'password' => md5($param['password']),
                'status' => empty($param['status']) ? 1 : $param['status'],
                'is_del' => 1,
                'role' => empty($param['role']) ? 1 : $param['role']
            ]);
            return true;
        } catch (\Exception $e) {
            app_fail(9996);
            return false;
        }
    }

    /**
     * 查看当前用户信息
     * User: zhouyao
     * Date: 2018/9/8
     * Time: 下午12:47
     * @param $param
     * @return array|null|\PDOStatement|string|\think\Model
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws \app\common\exception\AppException
     */
    public function edit($param)
    {
        if (empty($param) || !isset($param['id'])) {
            app_fail(9997);
        }

        // 查询当前用户是否存在
        $admin = self::$adminModel->where('is_del', '=', 1)
            ->where('id', '=', $param['id'])
            ->find();

        return $admin;
    }

    /**
     * 编辑管理员信息
     * User: zhouyao
     * Date: 2018/9/8
     * Time: 下午1:11
     * @param $param
     * @return bool
     * @throws \app\common\exception\AppException
     */
    public function update($param)
    {
        if (empty($param) || !isset($param['id'])) {
            app_fail( 9997);
        }

        // 拼装数据
        if (!empty($param['name'])) {
            $data['name'] = $param['name'];
        }
        if (!empty($param['username'])) {
            $data['user_name'] = $param['username'];
        }
        if (!empty($param['status'])) {
            $data['status'] = $param['status'];
        }
        if (!empty($param['role'])) {
            $data['role'] = $param['role'];
        }
        if (!empty($param['is_del'])) {
            $data['is_del'] = $param['is_del'];
        }
        if (!empty($param['password'])) {
            $data['password'] = md5($param['password']);
        }

        // 查询结果集
        $admin = self::$adminModel->save($data, ['id' => $param['id']]);
        return $admin ? true : false;
    }

    /**
     * 获取用户详情
     * User: zhouyao
     * Date: 2018/9/9
     * Time: 上午11:40
     * @param $param
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws \app\common\exception\AppException
     */
    public function getInfo($param)
    {
        $info = self::$adminModel->where('id', '=', $param['guid'])->find();
        $role = [$info->role];
        $username = $info->user_name;
        $data = [
            'last_time' => strtotime($info->update_time),   // 最后登录时间
            'username' => $username,    // 用户名
            'role' => $role             // 角色
        ];

        return $data;
    }

    /**
     * 编辑用户状态
     * User: zhouyao
     * Date: 2018/9/9
     * Time: 下午12:50
     * @param $param
     * @return bool
     * @throws \app\common\exception\AppException
     */
    public function changeStatus($param)
    {
        if (empty($param)) {
            app_fail(9777);
        }

        $admin = self::$adminModel->save(['status' => $param['status'] == 1 ? 2 : 1], ['id' => $param['id']]);
        return $admin ? true : false;
    }



}